package indi.lddsdu.spider.utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicInteger;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import us.codecraft.webmagic.Request;
import indi.lddsdu.spider.bean.RuntimeParameter;
import indi.lddsdu.spider.bean.Record;
import indi.lddsdu.spider.bean.UnDownloadUrl;
import indi.lddsdu.spider.dao.RecordDao;
import indi.lddsdu.spider.dao.UnDownloadUrlDao;
import indi.lddsdu.spider.enums.ContentType;
import indi.lddsdu.spider.exceptions.CreateFileException;
import indi.lddsdu.spider.exceptions.FileWriteException;


/**
 * 用于辅助Process存储数据   貌似这里的实际工作为Service层的工作
 * Created by jack on 18/6/4.
 */
@Component
public class ProcessUtil {

    private static Logger logger = LoggerFactory.getLogger(Process.class);
    private static final String PNG = "png";
    private static final String JPG = "jpg";
    @Autowired
    private  RecordDao recordDao;
    @Autowired
    private UnDownloadUrlDao unDownloadUrlDao;

    /**
     * 将数据存储进数据库，记录在数据库中  主要完成了对于所需要数据的抽取与写入，实际的数据库操作在recordDao中进行
     * @param pageRequestUrl
     * @param imgContent
     * @param picIndex
     */
    public  void dealWithPic(String pageRequestUrl, byte[] imgContent, AtomicInteger picIndex)
                                    throws CreateFileException, FileWriteException {

        //将文件写入到硬盘中
        String tail = PNG;
        if (pageRequestUrl.endsWith(JPG)){
            tail = JPG;
        }
        String imageName = String.format("%s.%s", getUUID(), tail);
        File file = new File(RuntimeParameter.persistenceImageFolder+ imageName);
        if(!file.exists()){
            try {
                file.createNewFile();
            } catch (IOException e) {
                throw new CreateFileException(file.getName());
            }
        }
        //TODO 这里的写法逻辑会有一定的问题，需要改正,对于错误的处理需要改正
        try {
            FileOutputStream fout = new FileOutputStream(file);
            fout.write(imgContent);
            fout.close();
        } catch (IOException e) {
            throw new FileWriteException(e, file.getName());
        }

        //将record信息写入到数据库中
        Record record = new Record("图片",pageRequestUrl, ContentType.IMAGE, file.getPath());
        recordDao.addRecord(record);
    }

    /**
     * 处理获取的纯文本
     * @param pageRequestUrl
     * @param
     * @param txtIndex
     * @throws CreateFileException
     * @throws FileWriteException
     */
    public  void dealWithText(String title,String pageRequestUrl, String text, AtomicInteger txtIndex)
            throws CreateFileException, FileWriteException {
        String fileName = String.format("%s.txt", getUUID());
        File file = new File(RuntimeParameter.persistenceHtmlFolder + fileName);
        if(!file.exists()){
            try {
                file.createNewFile();
            } catch (IOException e) {
                throw new CreateFileException(file.getName());
            }
        }
        //TODO 这里的写法逻辑会有一定的问题，需要改正
        try {
            FileWriter fileWriter = new FileWriter(file);
            fileWriter.write(text);
            fileWriter.close();
        } catch (IOException e) {
            throw new FileWriteException(e, file.getName());
        }
        //将record信息写入到数据库中
        Record record = new Record(title, pageRequestUrl, ContentType.TEXT, file.getPath());
        recordDao.addRecord(record);
    }

    /**
     * 获取uuid来组成文件名
     * @return
     */
    public String getUUID(){
        return UUID.randomUUID().toString();
    }

    /**
     * 将所所有的没有下载处理的url存储进数据库
     * @param unDownloadUrl
     */
    public void storeUnDownloadUrl(UnDownloadUrl unDownloadUrl){
        unDownloadUrlDao.addUnDownloadUrl(unDownloadUrl);
    }

    /**
     * 获取到所有的尚未下载的url
     * @return
     */
    public List<Request> findAllUnDownloadUrlAndThenDeleteAll(){
        List<Request> requestList  = unDownloadUrlDao.findAllUndownloadUrl();
        try {
            unDownloadUrlDao.deleteAll();
        } catch (Exception e) {
            logger.warn("error info " + e);
        }
        return requestList;
    }

    public boolean alreadyInDatabase(String url){
        return recordDao.alreadyInDatabase(url);
    }
}
